#!/usr/bin/python
#coding: utf-8
import socket
import time

ip = '127.0.0.1'
port = 60000
s = socket.socket()
def recvfile(filename):
	print 'server ready, now clinet recv file--->'
	f = open(filename,'wb')
	while True:
		data = s.recv(4096)
		if data == 'EOF':
			print 'recv file success!'
			break
		f.write(data)
	f.close()
def sendfile(filename):
	print 'server ready ,now clinet sending file--->'
	f = open(filename,'rb')
	while True:
		data = f.read(4096)
		if not data:
			break
		s.sendall(data)
	f.close()
	time.sleep(1)
	s.sendall('EOF')
	print 'send file success!'

def confirm(s,clinet_command):
	s.send(clinet_command)
	data = s.recv(4096)
	if data =='read':
		return True


try:
	s.connect((ip,port))
	while 1:
		clinet_command = raw_input('>>')
		if not clinet_command:
			continue

		action,filename = clinet_command.split()
		if action == 'put':
			path_filename = filename.split('/')[-1] 
			if confirm(s,clinet_command):
				sendfile(path_filename)
			else:
				print 'server get error!'
		elif action == 'get':
			if confirm(s,clinet_command):	
				recvfile(filename)
			else:
				print 'server get error'
		else:
			print 'command error!'
except socket.error,e:
	print 'get error as',e
finally:
	s.close()
